package com.duleme.servlet;

import com.duleme.common.EncodeUtils;
import com.duleme.common.EncryptUtil.MD5EncryptUtils;
import com.duleme.entity.Captcha;
import com.duleme.entity.User;
import com.duleme.entity.UserInfo;
import com.duleme.service.UserService;
import com.duleme.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "AlterPwd2Servlet",urlPatterns = "/alter/password2")
public class AlterPwd2Servlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        EncodeUtils.setEncoding(request,response);
        Captcha captcha = (Captcha) request.getSession().getAttribute("phoneCaptcha");
        PrintWriter writer = response.getWriter();
        if (captcha==null){
            writer.write(3);//没有获取到session的验证码,说明用户没有点击获取验证码
            System.out.println("没有获取到session的验证码");
        }else {
            String userAccount = captcha.getUserAccount();
            String password=request.getParameter("userPassword");
            UserService userService = new UserServiceImpl();
            if(userService.alterPassword(userAccount,password)){
                User user = userService.login(userAccount, MD5EncryptUtils.md5Encrypt(password));
                UserInfo userInfo = ((UserServiceImpl) userService).getUserInfo(userAccount, MD5EncryptUtils.md5Encrypt(password));
                request.getSession().setAttribute("user",user);
                request.getSession().setAttribute("userInfo",userInfo);
                writer.write("1");//修改成功
                System.out.println("修改成功");
                writer.close();
            }else {
                writer.write("2");
                System.out.println("修改失败");
                writer.close();
            }
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
